using BuildingBlocks.Presentation.Endpoints;
using BuildingBlocks.Presentation.Results;
using Mediator;
using Ordering.Application.Orders.CreateOrder;

namespace Ordering.Api.Endpoints.Orders;

internal sealed class CreateOrderEndpoint : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost(OrderRoutes.Base,
                async (CreateOrderRequest request, IMediator mediator, CancellationToken cancellationToken) =>
                {
                    var command = new CreateOrderCommand(
                        request.Items,
                        request.ShippingAddress,
                        request.Notes);

                    var result = await mediator.Send(command, cancellationToken);
                    return result.Match(
                        order => Results.Created($"{OrderRoutes.Base}/{order.UserId}", order),
                        ApiResponse.Problem);
                })
            .WithName("CreateOrder")
            .WithTags("Orders");
    }
}
